﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DIS_Web_Client.DIS_WS_BusinessLayer;
using DIS_WEB_Client.Helpers;
using DIS_WEB_Client.ShoppingCartModule;
using DIS_WEB_Client.ViewModels;

namespace DIS_WEB_Client.Controllers
{
    public class HomeController : BaseController
    {
        public ActionResult Index()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_INDEX
            };
            ValidateAuthentication();
            return View(CreateViewModel(data));
        }

        public void ValidateAuthentication()
        {
            // Checking user was login before
            var username = string.Empty;
            WebConfiguration.IsRequestAuthentication = ReviewCookieMember(ref username);
            WebConfiguration.UserNameAuthentication = username;
            if (WebConfiguration.IsRequestAuthentication)
            {
                // Checking if user is employee
                var employee = BusService.Instance.Employee_SelectByUserName(username);
                if (employee != null)
                {
                    var role = employee.Role.Name;
                    if (role.ToUpper().Contains("INTERNET"))
                    {
                        WebConfiguration.AllowAccessAdminCP = true;
                    }
                }
                else
                {
                    WebConfiguration.AllowAccessAdminCP = false;
                }
            }
        }

        /// <summary>
        /// Retrieve user in cookies
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        private bool ReviewCookieMember(ref string username)
        {
            var flag = false;
            HttpCookie SlmMemberCookie = new HttpCookie("SLMFMembers");
            SlmMemberCookie = Request.Cookies["SLMFMembers"];
            if (SlmMemberCookie != null && SlmMemberCookie.Value != "" &&
                 SlmMemberCookie.Value != null)
            {
                username = SlmMemberCookie.Value.ToString();
                flag = true;
            }
            return flag;
        }

        public ActionResult Products(int idCate)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_CATEGORY,
                IDCategory = idCate
            };
            return View(CreateViewModel(data));
        }

        public ActionResult ProductDetail(int id)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_PRODUCT,
                IntID = id
            };
            return View(CreateViewModel(data));
        }

        public ActionResult Register()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_REGISTER
            };
            return View(CreateViewModel(data));
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Register(FormCollection forms)
        {
            string fullname = forms.GetValues("fullname")[0];
            string phone = forms.GetValues("phone")[0];
            string address = forms.GetValues("address")[0];
            string email = forms.GetValues("email")[0];
            string username = forms.GetValues("username")[0];
            string password = forms.GetValues("password")[0];
            string PasswordEnc = Encryption.Encrypt(password);

            var customer = new CustomerDTO
            {
                Name = fullname,
                Phone = phone,
                Address = address,
                Email = email,
                UserName = username,
                Password = PasswordEnc
            };
            var result = BusService.Instance.Customer_Insert(customer);

            if (result)
            {
                SetCookieMember(username, PasswordEnc, "customer");
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ViewData["fullname"] = fullname;
                ViewData["phone"] = phone;
                ViewData["address"] = address;
                ViewData["email"] = email;
                ViewData["username"] = username;
                ViewData["password"] = password;
                ViewData["confirmpassword"] = forms.GetValues("confirmpassword")[0];
            }

            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_REGISTER
            };
            return View(CreateViewModel(data));
        }

        private void SetCookieMember(string username, string password, string role, bool rememberme = true)
        {
            HttpCookie SlmMemberCookie = new HttpCookie("SLMFMembers");
            HttpCookie SlmSessionId = new HttpCookie("SLMFSessionId");
            HttpCookie SlmRole = new HttpCookie("SLMFRole");

            DateTime dateSLMF = DateTime.Now;
            SlmMemberCookie.Value = username;
            SlmMemberCookie.Expires = dateSLMF.AddDays(3);

            SlmSessionId.Value = password;
            SlmSessionId.Expires = dateSLMF.AddDays(4);

            // Role
            SlmRole.Value = role;
            SlmRole.Expires = dateSLMF.AddDays(4);
            if (rememberme)
            {
                SlmMemberCookie.Expires = dateSLMF.AddDays(7);
                SlmSessionId.Expires = dateSLMF.AddDays(8);
                SlmRole.Expires = dateSLMF.AddDays(8);
            }
            Response.Cookies.Add(SlmMemberCookie);
            Response.Cookies.Add(SlmSessionId);
            Response.Cookies.Add(SlmRole);
        }

        public ActionResult Logout()
        {
            HttpCookie SlmMemberCookie = new HttpCookie("SLMFMembers");
            SlmMemberCookie = Request.Cookies["SLMFMembers"];
            if (SlmMemberCookie != null && SlmMemberCookie.Value != "" &&
                     SlmMemberCookie.Value != null)
            {
                SlmMemberCookie.Expires = new System.DateTime(2005, 1, 1);
                SlmMemberCookie.Value = null;
                Response.Cookies.Add(SlmMemberCookie);
            }

            return RedirectToAction("Index", "Home");
        }

        public ActionResult Login()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_REGISTER
            };
            return View(CreateViewModel(data));
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(FormCollection forms)
        {           
            string username = forms.GetValues("username")[0];
            string password = forms.GetValues("password")[0];
            string PasswordEnc = Encryption.Encrypt(password);

            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_REGISTER
            };

            // Checking if logged user is employee
            var employee = BusService.Instance.Employee_SelectByUserNameAndPassword(username, PasswordEnc);
            if (employee == null)
            {
                // customer
                var customer = BusService.Instance.Customer_SelectByUserNameAndPassword(username, PasswordEnc);
                if (customer != null)
                {
                    SetCookieMember(username, PasswordEnc, "customer");
                }
                else
                {
                    return View(CreateViewModel(data));
                }
            }
            else
            {
                // employee
                SetCookieMember(username, PasswordEnc, employee.Role.Name);
            }
            return RedirectToAction("Index", "Home");
        }

        public ActionResult AccountInfo(string username)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_ACCOUNTINFO,
                UserName = username
            };
            if (BusService.Instance.Employee_SelectByUserName(username) != null)
            {
                return RedirectToAction("Index", "Home");
            }
            ViewData["UpdateAccountInfo"] = null;
            return View(CreateViewModel(data));
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Update(FormCollection forms)
        {
            string username = forms.GetValues("username")[0];
            string fullname = forms.GetValues("fullname")[0];
            string phone = forms.GetValues("phone")[0];
            string address = forms.GetValues("address")[0];
            string email = forms.GetValues("email")[0];

            var customer = BusService.Instance.Customer_SelectByUserName(username);

            customer.Name = fullname;
            customer.Phone = phone;
            customer.Address = address;
            customer.Email = email;
            
            var result = BusService.Instance.Customer_Update(customer);

            if (result)
            {
                ViewData["UpdateAccountInfo"] = "Account's information has been updated successfully";
            }
            else
            {
                ViewData["UpdateAccountInfo"] = "Account's information has been updated failed";
            }

            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_ACCOUNTINFO,
                UserName = username
            };
            return View("AccountInfo", CreateViewModel(data));
        }

        ////////////////////// SHOPPING CART ////////////////////////
        public ActionResult AddToCart(int id, int idcate, int num = 0)
        {
            // Retrieve the food from the database 
            var addedItem = BusService.Instance.Item_SelectByID(id);

            // Add it to the shopping cart 
            var cart = ShoppingCart.GetCart(this.HttpContext);
            if (num == 0)
            {
                cart.AddToCart(addedItem);
            }
            else
            {
                cart.AddToCart(addedItem, num);
            }

            // Go back to the main store page for more shopping 
            // Set up our ViewModel 
            return RedirectToAction("Products", new { idCate = idcate });
        }

        [HttpPost]
        public ActionResult RemoveFromCart(int id)
        {
            // Remove the item from the cart 
            var cart = ShoppingCart.GetCart(this.HttpContext);

            // Get the name of the food to display confirmation 
            string foodName = BusService.Instance.Item_SelectByID(BusService.Instance.Cart_SelectByRecordID(id).ItemID).Name;

            // Remove from cart 
            cart.RemoveFromCart(id);

            // Display the confirmation message 
            var results = new ShoppingCartRemoveViewModel
            {
                Message = Server.HtmlEncode(foodName) +
                    " has been removed from your shopping cart.",
                CartTotal = cart.GetTotal(),
                ItemCount = 0,
                DeleteId = id
            };

            return Json(results);
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Approve(FormCollection forms)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_ORDER
            };

            var groupViewModel = CreateViewModel(data);
            string username = string.Empty;

            // Redirect to 
            if (!AuthenticateSession(ref username))
            {
                return View("Login", groupViewModel);
            }
            groupViewModel.UsersModel = RetrieveUsersByUserNameViewModel(username);

            return View("ApproveOrder", groupViewModel);
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AddOrder(FormCollection forms)
        {
            string idusers = forms.GetValues("Order_IDUsers")[0];
            string addressOfReceiver = forms.GetValues("AddressOfReceiver")[0];
            string nameOfReceiver = forms.GetValues("NameOfReceiver")[0];
            string phoneOfReceiver = forms.GetValues("PhoneOfReceiver")[0];

            // First insert new order
            var newOrder = new OrdersDTO
            {
                IDChemistWareHouse = BusService.Instance.ChemistWareHouse_SelectAll().First(n => n.Name.ToUpper().Contains("ONLINE")).ID,
                IDCustomer = int.Parse(idusers),
                OrderDate = DateTime.Now,
                IsVerified = false,
                IsShipped = false,
                IsPaid = false,
                AddressOfReceiver = addressOfReceiver,
                NameOfReceiver = nameOfReceiver,
                PhoneOfReceiver = phoneOfReceiver
            };

            var idInsertedOrder = BusService.Instance.Orders_Insert(ref newOrder);

            if (idInsertedOrder)
            {
                // Next insert order details
                var cart = ShoppingCart.GetCart(this.HttpContext);
                foreach (var item in cart.GetCartItems())
                {
                    var itemBuy = BusService.Instance.Item_SelectByID(item.ItemID);
                    var orderDetail = new OrderDetailDTO
                    {
                        IDOrder = newOrder.ID,
                        IDItem = item.ItemID,
                        Quantity = item.Count,
                        Price = itemBuy.Price
                    };
                    var result = BusService.Instance.OrderDetail_Insert(orderDetail);
                }
                cart.EmptyCart();
            }
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_ORDERHISTORY,
                IDCustomer = int.Parse(idusers)
            };
            ViewData["OrderResult"] = idInsertedOrder ? "Order successfull! we will process it as soon as possible" : "Order failed";
            return View("OrdersHistory", CreateViewModel(data));
        }

        public ActionResult OrdersHistory(string username)
        {
            var iduser = BusService.Instance.Customer_SelectByUserName(username).ID;
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_ORDERHISTORY,
                IDCustomer = iduser
            };
            return View(CreateViewModel(data));
        }

        public ActionResult SelectOrderDetailByIDOrder(int iduser, int idorder)
        {
            var data = new DataTransferViewModel
            {
                IDCustomer = iduser,
                IDOrder = idorder,
                EnumViewModelType = EnumViewModel.HOME_ORDERHISTORY_ORDERDETAIL,
            };
            return View("OrdersHistory", CreateViewModel(data));
        }
    }
}
